//获取权限方法
var userInfo = getAuthority();
var powerlist = JSON.parse(userInfo).permissions;
/*自定义函数判断权限*/
template.defaults.imports.hasPower = function(data){
    if(powerlist.includes(data)){
        return true;
    }
    return true;
};

layui.use(['layer', 'form', 'table', 'util', 'dtree'], function () {
    var $ = layui.jquery;
    var layer = layui.layer;
    var form = layui.form;
    var admin = layui.admin;
    var table = layui.table;
    var util = layui.util;
    var dtree = layui.dtree;

    var setting={//树设置
        regionSetting:{//区划树设置
            edit: {
                enable: true,
                showRemoveBtn: false,
                showRenameBtn: false,
                drag: {
                    isCopy: true,
                    isMove: false,
                    prev: false,
                    next: false,
                    inner: false
                }
            },
            data: {
                key: {
                    children: "sub"
                },
                simpleData: {
                    enable: true
                }
            },
            callback: {
                onExpand: onExpandRegionTree,
                onClick: zTreeRegionOnClick
            },
            view: {
                showIcon: false,
                showLine: false
            }
        },
        orgionRegionSetting:{//原点区划树设置
            edit: {
                enable: true,
                showRemoveBtn: false,
                showRenameBtn: false,
                drag: {
                    isCopy: true,
                    isMove: false,
                    prev: false,
                    next: false,
                    inner: false
                }
            },
            data: {
                key: {
                    children: "sub"
                },
                simpleData: {
                    enable: true
                }
            },
            callback: {
                onExpand: onExpandOrgionRegionTree,
                onClick: zTreeOrgionOnClick
            },
            view: {
                showIcon: false,
                showLine: false
            }
        },
        orgionRegionSetting_regionChange:{//原点区划树设置-区划变更弹窗使用
            edit: {
                enable: true,
                showRemoveBtn: false,
                showRenameBtn: false,
                drag: {
                    isCopy: true,
                    isMove: false,
                    prev: false,
                    next: false,
                    inner: false
                }
            },
            data: {
                key: {
                    children: "sub"
                },
                simpleData: {
                    enable: true
                }
            },
            callback: {
                onExpand: onExpandOrgionRegionTree_regionChange,
                onClick: zTreeOrgionOnClick_regionChange
            },
            view: {
                showIcon: false,
                showLine: false
            }
        }
    }
    var addRegion={//新增区划参数
        originCode:'',//原点行政区划代码
        parentRegion:''//上级区划代码
    }
    var selectedCatalog = "";//选中的配置
    var selectRegionRowObj = {};//选中的区划行
    var regionType = [];//区划配置类型

    var regionChange={//区划变更参数
        subrgid :''
    }

    if(userInfo){
        selectedCatalog = window.regionSelectedCatalog;  // 获取列表页面传递的数据，也可以使用top.xxx
        var access_token = localStorage.getExpire("access_token");
        var token_type = localStorage.getExpire("token_type");
        Authorization = token_type+" "+access_token;

        getRegionManagePower();
        getOrgionTreeTablePower();
        initRegionTree();
    }


    function getRegionManagePower() {
        var str = template("regionmanage-tmpl",{});
        document.getElementById("regionmanage-tmpl-box").innerHTML = str;
    }
    function getOrgionTreeTablePower() {
        var str = template("tableBarAuth-tmp",{});
        document.getElementById("tableBarAuth").innerHTML = str;
    }
    // 添加
    $('#add-btn-template-regionManage').click(function () {
        showRegionAddModle();
    });
    // 编辑
    $('#edit-btn-regionManage').click(function () {
        //返回第一个被选中的行或如果没有选中的行则返回null。
        selectRegionRowObj = $('#regionManageTreeTable').datagrid('getSelected');
        if(selectRegionRowObj!=null){
            showRegionEditModle(selectRegionRowObj);
        }else{
            layer.msg('请先选中区划', {icon: 2});
        }
    });
    // 删除
    $('#delete-btn-regionManage').click(function () {
        //返回第一个被选中的行或如果没有选中的行则返回null。
        selectRegionRowObj = $('#regionManageTreeTable').datagrid('getSelected');
        if(selectRegionRowObj!=null){
            showRegionDeleteModle(selectRegionRowObj);
        }else{
            layer.msg('请先选中区划', {icon: 2});
        }
    });

    $('#change-region-btn').click(function () {
        selectRegionRowObj = $('#regionManageTreeTable').datagrid('getSelected');
        if(selectRegionRowObj!=null){
            showRegionChangeModel(selectRegionRowObj);
        }else{
            layer.msg('请先选中区划', {icon: 2});
        }
    });

    //导入区划树
    $('#import-btn-orgionRegion').click(function () {
        openImportRegionModel();
    });

    // 区划变更工具条点击事件
    table.on('tool(regionChangeTable)', function (obj) {
        var data = obj.data;
        var layEvent = obj.event;
        if (layEvent === 'deleteChange') { // 删除
            showDeleteChangeModel(data);
        }
    });

    function getRegionTree(parcode,callback){
        var req={
            rcId : selectedCatalog.id,
            regionCode: parcode||"",
            regionCodeType:selectedCatalog.regionType
        };
        axios.get(regionUrl.info.queryRegion,{
            params: req,
            headers:{
                'Authorization':Authorization
            }
        })
            .then(function (response) {
                if(response.status == 200 &&response.data.message == "success"){
                    var data = response.data.data;
                    for(var i in data){
                        data[i].children=[{}];
                        data[i].isParent = true;
                        data[i].state = "closed";
                    }
                    callback(data);
                }
            })
            .catch(function (error) {
                console.log(error);
            });
    }
    function initRegionTree(){
        getRegionType();
        getRegionTree('',function(data){
            renderTreeTable(data);
        })
    }
    /*获取区划类型*/
    function getRegionType() {
        axios.get(regionUrl.info.regionType,{
            headers:{
                'Authorization':Authorization
            }
        })
            .then(function (response) {
                if(response.status == 200 &&response.data.message == "success"){
                    regionType = response.data.data;

                }
            })
            .catch(function (error) {
                console.log(error);
            });
    }

    //渲染树表格
    function renderTreeTable(data) {
        $('#regionManageTreeTable').treegrid({
            idField:'id',
            treeField:'name',
            loadFilter: lasyLoadTreeTable,
            data:data,
            columns:[[
                {field:'name',title:'名称',width:200},
                {field:'parCodeName',title:'上级区划',width:150},
                {field:'originName',title:'原点区划',width:150},
                {field:'x',title:'X坐标',width:80},
                {field:'y',title:'Y坐标',width:80},
                {field:'regionCodeType',title:'行政区域类型',width:200,formatter: function(value,row,index){
                    for(var i in regionType){
                        if(regionType[i].value == row.regionCodeType){
                            return regionType[i].regionType;
                        }
                    }
                }},
                {field:'memo',title:'描述',width:250}
            ]]
        });
    }

    //树表格
    function lasyLoadTreeTable(data,parentId){
        function setData(data){
            var todo = [];
            for(var i=0; i<data.length; i++){
                todo.push(data[i]);
            }
            while(todo.length){
                var node = todo.shift();
                if (node.children && node.children.length){
                    node.state = 'closed';
                    node.children1 = node.children;
                    node.children = [];
                    todo = todo.concat(node.children1);
                }
            }

            return data;
        }
        setData(data);
        var tg = $(this);
        var opts = tg.treegrid('options');

        opts.onBeforeExpand = function(row) {
            if (row.children.length<1) {
                getRegionTree(row.code, function (newRegionCata) {
                    tg.treegrid('append', {
                        parent: row[opts.idField],
                        data: newRegionCata
                    });

                    row.children1 = undefined;
                    tg.treegrid('expand', row[opts.idField]);

                })
            };
            return row.children1 == undefined;
        }
        return data;

    }

    // 添加弹窗
    function showRegionAddModle() {
        admin.open({
            type: 1,
            title: '新增行政区划',
            area: ['350px', '480px'],
            offset:'auto',
            content: $('#addRegionManage').html(),
            success: function (layero, dIndex) {
                addRegion.originCode = '';
                addRegion.parentRegion = '';
                lazyLoadRegionTree();
                lazyLoadOrgionRegionTree();
                $("#parentRegionName").click(function () {
                    $("#RegionTree").css('display','block');
                })
                $("#orgionRegionName").click(function () {
                    $("#orgionRegionTree").css('display','block');
                })

                var addregionType = {
                    regionType:regionType
                }
                var regionTypeStr = template("region-type-tmpl",addregionType);
                document.getElementById("addRegionCodeTypeBox").innerHTML = regionTypeStr;

                form.render('select'); //刷新select选择框渲染
                form.on('submit(regionEditSubmit)', function (data) {
                    var req = data.field;
                    // if(addRegion.originCode==null||addRegion.originCode==""){
                    //     layer.msg('请设置原点区划', {icon: 2});
                    //     return false;
                    // }
                    if(addRegion.parentRegion==null||addRegion.parentRegion==""){
                        layer.msg('请设置上级区划', {icon: 2});
                        return false;
                    }
                    req.flag = 0;
                    req.originCode = addRegion.originCode;
                    req.rcid = selectedCatalog.id;
                    req.parCode = addRegion.parentRegion;

                    axios({
                        method: 'POST',
                        url:regionUrl.info.addRegion,
                        data:$.param(req),
                        headers:{
                            'Authorization':Authorization
                        }
                    })
                        .then(function (response) {
                            if(response.status == 200 &&response.data.message == "success"){
                                layer.close(dIndex);
                                layer.closeAll('loading');
                                layer.msg(response.data.message, {icon: 1});
                                initRegionTree();
                            }else{
                                layer.closeAll('loading');
                                layer.msg(response.data.message, {icon: 2});
                            }
                        })
                        .catch(function (error) {
                            console.log(error);
                        });
                    return false;
                });
            }
        });
    }
    //编辑弹窗
    function showRegionEditModle(selectedRegion) {
        admin.open({
            type: 1,
            title: '编辑行政区划',
            area: ['350px', '480px'],
            offset:'auto',
            content: $('#addRegionManage').html(),
            success: function (layero, dIndex) {
                addRegion.originCode = '';
                $("#parentRegionName").text(selectedRegion.parCodeName);
                addRegion.parentRegion = selectedRegion.parCode;
                $("#orgionRegionName").text(selectedRegion.originName);
                addRegion.originCode = selectedRegion.originCode;

                lazyLoadRegionTree();
                lazyLoadOrgionRegionTree();
                $("#parentRegionName").click(function () {
                    $("#RegionTree").css('display','block');
                })
                $("#orgionRegionName").click(function () {
                    $("#orgionRegionTree").css('display','block');
                })
                var addregionType = {
                    regionType:regionType
                }
                var regionTypeStr = template("region-type-tmpl",addregionType);
                document.getElementById("addRegionCodeTypeBox").innerHTML = regionTypeStr;
                form.render('select'); //刷新select选择框渲染
                form.val('regionForm',selectedRegion);

                form.on('submit(regionEditSubmit)', function (data) {
                    var req = data.field;
                    // if(addRegion.originCode==null||addRegion.originCode==""){
                    //     layer.msg('请设置原点区划', {icon: 2});
                    //     return false;
                    // }
                    req.flag = 0;
                    req.originCode = addRegion.originCode;
                    req.rcid = selectedCatalog.id;
                    req.parCode = addRegion.parentRegion;
                    req.id = selectedRegion.id;
                    req.version = selectedRegion.version;

                    axios({
                        method: 'PUT',
                        url:regionUrl.info.editRegion,
                        data:$.param(req),
                        headers:{
                            'Authorization':Authorization
                        }
                    })
                        .then(function (response) {
                            if(response.status == 200 &&response.data.message == "success"){
                                layer.close(dIndex);
                                layer.closeAll('loading');
                                layer.msg(response.data.message, {icon: 1});
                                initRegionTree();
                            }else{
                                layer.closeAll('loading');
                                layer.msg(response.data.message, {icon: 2});
                            }
                        })
                        .catch(function (error) {
                            console.log(error);
                        });
                    return false;
                });
            }
        });
    }

    // 删除区划
    function showRegionDeleteModle(selectRegionRowObj) {
        layer.confirm('确定要删除区划“' + selectRegionRowObj.name + '”吗？', {
            skin: 'layui-layer-admin',
            shade: .1,
            cancel: function(index, layero){
                layer_popup = false;//取消操作，点击右上角的X去掉弹窗限制
            }
        }, function (i) {
            layer.close(i);
            layer.load(2);
            axios({
                method: 'delete',
                url:regionUrl.info.deleteRegion+selectRegionRowObj.id,
                headers:{
                    'Authorization':Authorization
                }
            })
                .then(function (res) {
                    if (res.status == 200&&res.data.message=="success") {
                        layer.closeAll('loading');
                        layer.msg("成功删除", {icon: 1});
                        initRegionTree();
                    } else {
                        layer.closeAll('loading');
                        layer.msg(res.data.message, {icon: 2});
                    }
                })
                .catch(function (err) {
                    console.log(err);
                })
        });
    }

    //懒加载区划树(选择上级区划时用)
    function lazyLoadRegionTree() {
        var req={
            rcId : selectedCatalog.id,
            regionCode: "",
            regionCodeType:selectedCatalog.regionType
        };
        axios.get(regionUrl.info.queryRegion,{
            params: req,
            headers:{
                'Authorization':Authorization
            }
        })
            .then(function (response) {
                if(response.status == 200 &&response.data.message == "success"){
                    var datas = response.data.data;
                    if (datas.length > 0) {
                        for (const row of datas) {
                            row.isParent = true;
                            row.sub = []; //存放子节点
                            row.drag = true;
                        }
                    }
                    $.fn.zTree.init($("#RegionTree"), setting.regionSetting, datas);
                }
            })
            .catch(function (error) {
                console.log(error);
            });
    }

    //懒加载原点区划树
    function lazyLoadOrgionRegionTree() {
        var req={
            regionCode : '',
        };
        axios.get(regionUrl.origion.queryOrigion,{
            params: req,
            headers:{
                'Authorization':Authorization
            }
        })
            .then(function (response) {
                if(response.status == 200 &&response.data.message == "success"){
                    var datas = response.data.data;
                    if (datas.length > 0) {
                        for (const row of datas) {
                            row.isParent = true;
                            row.sub = []; //存放子节点
                            row.drag = true;
                        }
                    }
                    $.fn.zTree.init($("#orgionRegionTree"), setting.orgionRegionSetting, datas);
                }
            })
            .catch(function (error) {
                console.log(error);
            });

    }

    //展开下级原点区划
    function onExpandOrgionRegionTree(event, treeId, treeNode) {
        if(treeNode.sub.length==0){
            var req={
                regionCode : treeNode.code,
            };
            axios.get(regionUrl.origion.queryOrigion,{
                params: req,
                headers:{
                    'Authorization':Authorization
                }
            })
                .then(function (response) {
                    if(response.status == 200 &&response.data.message == "success"){
                        var datas = response.data.data;
                        if (datas.length > 0) {
                            for (const row of datas) {
                                row.isParent = true;
                                row.sub = []; //存放子节点
                                row.drag = true;
                            }
                        }
                        const treeObj = $.fn.zTree.getZTreeObj("orgionRegionTree");
                        treeObj.addNodes(treeNode, datas);
                    }
                })
                .catch(function (error) {
                    console.log(error);
                });
        }

    }

    //原点区划选中事件
    function zTreeOrgionOnClick(event, treeId, treeNode) {
        $("#orgionRegionName").text(treeNode.name);
        addRegion.originCode=treeNode.code;
        $("#orgionRegionTree").css('display','none');
    }

    //展开下级区划
    function onExpandRegionTree(event, treeId, treeNode){
        if(treeNode.sub.length==0){
            var req={
                rcId : selectedCatalog.id,
                regionCode: treeNode.code,
                regionCodeType:selectedCatalog.regionType
            };
            axios.get(regionUrl.info.queryRegion,{
                params: req,
                headers:{
                    'Authorization':Authorization
                }
            })
                .then(function (response) {
                    if(response.status == 200 &&response.data.message == "success"){
                        var datas = response.data.data;
                        if (datas.length > 0) {
                            for (const row of datas) {
                                row.isParent = true;
                                row.sub = []; //存放子节点
                                row.drag = true;
                            }
                        }
                        const treeObj = $.fn.zTree.getZTreeObj("RegionTree");
                        treeObj.addNodes(treeNode, datas);
                    }
                })
                .catch(function (error) {
                    console.log(error);
                });
        }
    }

    //区划选中事件
    function zTreeRegionOnClick(event, treeId, treeNode){
        $("#parentRegionName").text(treeNode.name);
        addRegion.parentRegion=treeNode.code;
        $("#RegionTree").css('display','none');
    }

    //打开区划变更弹窗
    function showRegionChangeModel(obj) {
        admin.open({
            type: 1,
            title: '区划变更',
            area: ['1000px', '550px'],
            offset:'auto',
            content: $('#RegionChangeModel').html(),
            success: function (layero, dIndex) {
                queryChange(obj.id);
                getChangeTypeData();
                lazyLoadOrgionRegionTree_regionChange();
                $("#changeRegionName").click(function () {
                    $("#changeRegionTree").css('display','block');
                })
                form.on('submit(regionChangeSubmit)', function (data) {
                    if(regionChange.subrgid==null||regionChange.subrgid==""){
                        layer.msg('请设置当前变更行政区划', {icon: 2});
                        return false;
                    }
                    var req = {
                        changetype:data.field.changetype ,
                        prrgid:obj.id,
                        subrgid:regionChange.subrgid
                    }
                    axios({
                        method: 'POST',
                        url:regionUrl.change.addChange,
                        data:$.param(req),
                        headers:{
                            'Authorization':Authorization
                        }
                    })
                        .then(function (response) {
                            if(response.status == 200 &&response.data.message == "success"){
                                layer.closeAll('loading');
                                layer.msg(response.data.message, {icon: 1});
                                queryChange(obj.id);
                            }else{
                                layer.closeAll('loading');
                                layer.msg(response.data.message, {icon: 2});
                            }
                        })
                        .catch(function (error) {
                            console.log(error);
                        });
                    return false;
                });
            }
        });
    }

    //获取变更类型
    function getChangeTypeData() {
        axios.get(regionUrl.change.changeType,{
            headers:{
                'Authorization':Authorization
            }
        })
            .then(function (response) {
                if(response.status == 200 &&response.data.message == "success"){
                    var changeType = response.data;
                    var str = template("region-changetype-tmpl",changeType);
                    document.getElementById("changetypebox").innerHTML = str;
                    form.render('select')
                }
            })
            .catch(function (error) {
                console.log(error);
            });
    }

    //懒加载原点区划树
    function lazyLoadOrgionRegionTree_regionChange() {
        var req={
            regionCode : '',
        };
        axios.get(regionUrl.origion.queryOrigion,{
            params: req,
            headers:{
                'Authorization':Authorization
            }
        })
            .then(function (response) {
                if(response.status == 200 &&response.data.message == "success"){
                    var datas = response.data.data;
                    if (datas.length > 0) {
                        for (const row of datas) {
                            row.isParent = true;
                            row.sub = []; //存放子节点
                            row.drag = true;
                        }
                    }
                    $.fn.zTree.init($("#changeRegionTree"), setting.orgionRegionSetting_regionChange, datas);
                }
            })
            .catch(function (error) {
                console.log(error);
            });

    }

    //展开下级原点区划
    function onExpandOrgionRegionTree_regionChange(event, treeId, treeNode) {
        if(treeNode.sub.length==0){
            var req={
                regionCode : treeNode.code,
            };
            axios.get(regionUrl.origion.queryOrigion,{
                params: req,
                headers:{
                    'Authorization':Authorization
                }
            })
                .then(function (response) {
                    if(response.status == 200 &&response.data.message == "success"){
                        var datas = response.data.data;
                        if (datas.length > 0) {
                            for (const row of datas) {
                                row.isParent = true;
                                row.sub = []; //存放子节点
                                row.drag = true;
                            }
                        }
                        const treeObj = $.fn.zTree.getZTreeObj("changeRegionTree");
                        treeObj.addNodes(treeNode, datas);
                    }
                })
                .catch(function (error) {
                    console.log(error);
                });
        }

    }

    //原点区划选中事件
    function zTreeOrgionOnClick_regionChange(event, treeId, treeNode) {
        $("#changeRegionName").text(treeNode.name);
        regionChange.subrgid=treeNode.id;
        $("#changeRegionTree").css('display','none');
    }

    //区划变更查询
    function queryChange(prrgid) {
        var req = {
            prrgid:prrgid
        }
        axios.get(regionUrl.change.queryChange,{
            params:req,
            headers:{
                'Authorization':Authorization
            }
        })
            .then(function (response) {
                if(response.status == 200 &&response.data.message == "success"){
                   var tableData = response.data.data;
                    table.render({
                        elem: '#regionChangeTable',
                        size: 'sm', //小尺寸的表格
                        page: false,
                        cellMinWidth: 40,
                        data:tableData,
                        cols: [[
                            {type:'numbers', title: '编号'},
                            {field: 'subname', align: 'center', title: '行政区划',minWidth: 80},
                            {field: 'changeTypeName', align: 'center', title: '变更类型',minWidth: 120},
                            {field: 'memo', align: 'center', title: '描述'},
                            {field: 'year', align: 'center', title: '操作',toolbar: '#region-change-table-template-box', minWidth: 80}
                        ]]
                    });
                }
            })
            .catch(function (error) {
                console.log(error);
            });
    }

    // 删除区划变更
    function showDeleteChangeModel(data){
        layer.confirm('确定要删除该变更信息吗？', {
            skin: 'layui-layer-admin',
            shade: .1,
            cancel: function(index, layero){
                layer_popup = false;//取消操作，点击右上角的X去掉弹窗限制
            }
        }, function (i) {
            layer.close(i);
            layer.load(2);
            axios({
                method: 'delete',
                url:regionUrl.change.deleteChange+data.id,
                headers:{
                    'Authorization':Authorization
                }
            })
                .then(function (res) {
                    if (res.status == 200&&res.data.message=="success") {
                        layer.closeAll('loading');
                        layer.msg("成功删除", {icon: 1});
                        queryChange(selectRegionRowObj.id);
                    } else {
                        layer.closeAll('loading');
                        layer.msg(res.data.message, {icon: 2});
                    }
                })
                .catch(function (err) {
                    console.log(err);
                })
        });
    }

    /*显示导入指标弹窗*/
    function openImportRegionModel() {
        window.importRegionIsOk = false;
        admin.open({
            title: '导入区划树',
            url: './importRegion.html',
            end: function () {
                window.inslideTime = null;
                getCatalogOneInfo();
                initRegionTree();
            },
            success: function (layero, dIndex) {
                // 弹窗超出范围不出现滚动条
                $(layero).children('.layui-layer-content').css('overflow', 'visible');
                if (window.importRegionIsOk) {  // 判断表单操作成功标识，也可以使用top.xxx
                    initRegionTree();
                }
            }
        });
    }

    /*查询单个区划配置信息*/
    function getCatalogOneInfo() {
        var req={
            id: selectedCatalog.id
        };
        axios.get(regionUrl.catalog.selectOne,{
            params: req,
            headers:{
                'Authorization':Authorization
            }
        })
            .then(function (response) {
                if(response.status == 200 &&response.data.message == "success"){
                    var data = response.data.data;
                    selectedCatalog = data;
                    window.regionSelectedCatalog = data;
                    initRegionTree();
                }
            })
            .catch(function (error) {
                console.log(error);
            });
    }



})